<template>
  <div class="app-container BlogAdd">
    <div class="top">
      <div class="title">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-input placeholder="请输入标题" v-model="sqlData.title" clearable></el-input>
          </el-col>
          <el-col :span="8">
            <hz-select
              clearable
              placeholder="请选择文章分类"
              :value.sync="sqlData.essayType"
              :options='classifyOptions'
            ></hz-select>
          </el-col>
          <el-col :span="8">
            <hz-select
              clearable
              isMultiple
              isCollapseTags
              placeholder="请选择文章标签"
              :value.sync="sqlData.essayTag"
              :options='tagOptions'
            ></hz-select>
          </el-col>
          <!-- <el-col :span="6">

          </el-col> -->
        </el-row>
        <el-upload
              class="avatar-uploader"
              :headers='{Authorization }'
              :action='$upLoadApi + "/upload"'
              :show-file-list="false"
              :on-success="(res)=>{sqlData.coverImg = res.url}">
                <el-tooltip class="item" effect="dark" content="重新上传文章封面图片" placement="top" v-if="sqlData.coverImg">
                  <img  style="height:6rem" :src="sqlData.coverImg" class="avatar">
                </el-tooltip>
                <el-button type="primary" class='uploadImgBtn' v-else>上传文章封面<i class="el-icon-upload el-icon--right"></i></el-button>

                <!-- <i v-else class="el-icon-plus avatar-uploader-icon"></i> -->
              </el-upload>
      </div>
      <div class="btn">
        <el-button type="info" plain size="small" @click="saveArticle(2)" v-if="sqlData.essayState === 2 || $route.name === 'EssayAdd'">保存草稿</el-button>
        <!-- 新增按钮进入页面后展示的按钮 -->
        <el-button type="primary" size="small" @click="saveArticle(1)" >发布文章</el-button>
      </div>
    </div>
    <!-- markdown编辑器 -->
    <mavon-editor ref="md" class="md" v-model="sqlData.markdown" @imgAdd="imgAdd" @imgDel="imgDel" @save="saveArticle(1)"/>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { getBgStatus } from '../../../utils/validate'
import { postAddBlog, getClassifyList, getEssayById, postUpdateEssay,getTagList } from '@/api/modules/blog'
import { postUploadImg } from '../../../api/common'
import HzSelect from '../../../components/compon/HzSelect.vue'
export default {
  components: { HzSelect },
  name: 'BlogAdd',
  data () {
    return {
      classifyOptions: [],
      tagOptions:[],
      Authorization:'',
      sqlData: {
        essayTag:'',
        essayType: '',
        markdown: '',
        html: '',
        coverImg: '', // 封面图片
        title: '' // 文章标题
      }
    }
  },
  created () {
    Object.assign(this.sqlData, this.$route.params)
    this.Authorization =  'Bearer ' + getToken() 
    this.getClassify()
    if (this.$route.name === 'EssayUpdate') { this.getSginEssay() }
  },
  methods: {
    //  修改获取单个文章
    async getSginEssay () {
      const res = await getEssayById(this.sqlData)
      Object.assign(this.sqlData, res)
    },
    //  获取文章类型数据 & 标签数据
    async getClassify () {
      const res = await getClassifyList()
      this.classifyOptions = res.rows
      const data = await getTagList()
      this.tagOptions = data.rows
      // this.sqlData.essayType = res.rows[0].value
    },
    // 上传文章封面图片成功
    handleAvatarSuccess (res, file) {
      this.sqlData.coverImg = URL.createObjectURL(file.raw)
    },
    // 删除文章封面图片
    handleRemove (file) {
      console.log(file)
    },
    // 获取文章
    getArticle () {

    },
    // 保存文章
    async saveArticle (state) {
      // var htmlCode = this.$refs.md.d_render
      // var markdownCode = this.$refs.md.d_value

      // 校验数据是否填写完成
      this.sqlData.essayTypeName = getBgStatus(this.sqlData.essayType,this.classifyOptions)
      this.sqlData.essayTagName = []
      this.sqlData.essayTag.forEach((item,index) => {
        this.sqlData.essayTagName[index] = getBgStatus(item,this.tagOptions)
      });
      this.sqlData.html = this.$refs.md.d_render
      for (const key in this.sqlData) {
        if (this.sqlData[key].length === 0) {
          this.$message({
            type: 'warning',
            message: '请将数据填写完整'
          })
          return false
        }
      }
      this.sqlData.essayState = state
      this.sqlData.pageView = this.sqlData.pageView || 0
      
      // 判断当前是哪个页面，调用add、update的api接口
      if (this.$route.name === 'EssayUpdate') {
        // 编辑
        this.editeEssay(postUpdateEssay)
      } else {
        // 新增
        this.editeEssay(postAddBlog)
      }
    },
    // 保存文章：essayState判断存储哪个类型：2 草稿、1 发布
    async editeEssay (apiName) {
      if (this.sqlData.essayState === 2) {
        await apiName(this.sqlData)
        this.$message({
          type: 'success',
          message: '已保存至草稿箱'
        })
        this.$router.push({ name: 'Essay' })
        this.$store.dispatch('tagsView/delView', this.$route)
      } else {
        this.$confirm('确认发布, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          await apiName(this.sqlData)
          this.$router.push({ name: 'Essay' })
          this.$store.dispatch('tagsView/delView', this.$route)
        })
      }
    },
    // 添加图片
    async imgAdd (pos, file) {
      console.log('pos:' + pos)
      // 第一步.将图片上传到服务器.
      var formdata = new FormData()
      formdata.append('file', file)
      const { url } = await postUploadImg(formdata)
      console.log(url)
      this.$refs.md.$img2Url(pos, url)
      // file_axios({
      //   url: '/api/img_upload',
      //   method: 'post',
      //   data: formdata
      // }).then((response) => {
      //   // 第二步.将返回的url替换到文本原位置
      //   var url = response.data
      //   // 通过引入对象获取: import {mavonEditor} from ... 等方式引入后，此时$vm即为mavonEditor
      //   // 通过$refs获取: html声明ref : <mavon-editor ref=md ></mavon-editor>， 此时$vm为 this.$refs.md`
      //   this.$refs.md.$img2Url(pos, url)
      // })
    },
    // 删除图片
    imgDel (pos) {
      console.log('imgDel pos:' + pos)
    },
    // 多张图片
    mulUploadimg () {
      // 第一步.将图片上传到服务器.
      var formdata = new FormData()
      for (var _img in this.img_file) {
        // debugger
        // 后台需要图片的key一致
        formdata.append('pics', this.img_file[_img])
      }
      // file_axios({
      //   url: '/api/mul_img_upload',
      //   method: 'post',
      //   data: formdata
      // }).then((res) => {
      //   /**
      //      * 例如：返回数据为 res = [[pos, url], [pos, url]...]
      //      * pos 为原图片标志（0）
      //      * url 为上传后图片的url地址
      //      */
      //   // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
      //   var idx_url = res.data
      //   idx_url.forEach(item => {
      //     // 通过引入对象获取: import {mavonEditor} from ... 等方式引入后，此时$vm即为mavonEditor
      //     // 通过$refs获取: html声明ref : <mavon-editor ref=md ></mavon-editor>， 此时$vm为 this.$refs.md`
      //     this.$refs.md.$img2Url(item[0], item[1])
      //   })
      // })
    },
    // 多张图片
    imgDelMul (pos) {
      console.log('imgDel pos:' + pos)
      delete this.img_file[pos]
    }
  }
}
</script>

<style  lang="scss" scoped>
.BlogAdd{
  .unplodBox{
    display: flex;
    justify-content: center;
  }
  .avatar-uploader /deep/ .el-upload {
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader img{
    border: 1px dashed #d9d9d9;

  }
  /deep/ .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    min-width: 2rem;
    max-height: 2rem;
    line-height: 2rem;
    text-align: center;
  }
  .avatar {
    min-width: 2rem;
    max-height: 2rem;
    display: block;
  }
  .top{
    display: flex;
    justify-content: space-between;
    padding-bottom: 10px;
    .title{
      // white-space: nowrap;
      display: flex;
      align-items: center;
      span{
        width: 120px;
        white-space: nowrap;
      }
      .uploadImgBtn{
        margin-left: 20px;
      }
    }
  }
  .md{
    z-index: 0 !important;
    /deep/.v-note-edit{
      height: calc(100vh - 225px);
      overflow: auto;
    }
    /deep/.v-note-show{
      height: calc(100vh - 225px);
      overflow: auto;
    }
  }
}
</style>
